package menu_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"benkendSystem/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

// AddMenu 添加菜单
func AddMenu(c *gin.Context) {
	in := new(AddMenuRequest)
	err := c.ShouldBindJSON(in)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "参数错误",
		})
		return
	}
	// 判断菜单是否存在
	var cnt int64
	err = database.DB.Model(new(models.Menu)).Where("name = ?", in.Name).Count(&cnt).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	if cnt > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "菜单已存在",
		})
		return
	}
	// 初始化id
	err = utils.InitSnowflake(1)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	id := utils.GenerateID()
	// 新增数据
	err = database.DB.Create(&models.Menu{
		ID:            id,
		Name:          in.Name,
		Icon:          in.Icon,
		ParentID:      in.ParentId,
		Order:         in.Order,
		Path:          in.Path,
		Level:         in.Level,
		ComponentName: in.ComponentName,
	}).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "操作成功",
	})
}
